<script setup>
import _ from 'lodash'
import {computed, onMounted, ref, watch} from "vue";
import {api} from "@jzl/api";

const emit = defineEmits(['close']);
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  modId: {
    type: Number,
    default: 0
  },
  pid: {
    type: Number,
    default: 0
  },
  isView: {
    type: Boolean,
    default: false
  }
})

const formRef = ref(null)
const loading = ref(false)

const form = ref({
  dept_code: '',
  dept_name: '',
  remark: '',
  parent_id: -1,
})

const rules = ref({
  dept_code: [
    {required: true, message: '请输入编码', trigger: 'blur'}
  ],
  dept_name: [
    {required: true, message: '请输入名称', trigger: 'blur'}
  ]
})

const isEdit = computed(() => {
  return props.modId && form.value.dept_id;
})

watch(() => props.show, (val) => {
  if (val) init()
})

onMounted(() => {
  init()
})

const reset = () => {
  form.value.dept_code = '';
  form.value.dept_name = "";
  formRef.value?.resetFields();
}

const init = async () => {
  reset();
  if (props.modId) {
    let dept = await api.dept.getDept(props.modId);
    form.value = dept;
  } else {
    form.value.dept_code = $utils.getNanoid(); // uuidv4().replace(/-/g, '');
    form.value.parent_id = props.pid;
  }
}

const submit = async () => {
  let valid = await formRef.value.validate();

  if (valid) {
    await _submit();
  }
}

const _submit = async () => {
  loading.value = true;

  let ret = false;
  let kv = _.cloneDeep(form.value);

  if (isEdit.value) {
    ret = await api.dept.updateDept(kv);
  } else {
    ret = await api.dept.createDept(kv);
  }

  if (ret) {
    $jui.toast('操作成功！');
    close(true);
  }

  loading.value = false;
}

const close = (flag) => {
  emit('close', flag);
}

</script>

<template>
  <el-form
    :model="form"
    ref="formRef"
    :rules="rules"
    style="min-width:500px;"
    label-width="120px"
  >
    <el-form-item
      label="码值"
      prop="dept_code"
    >
      <el-input
        v-model="form.dept_code"
        :disabled="isView"
      ></el-input>
    </el-form-item>
    <el-form-item
      label="名称"
      prop="dept_name"
    >
      <el-input
        v-model="form.dept_name"
        :disabled="isView"
      ></el-input>
    </el-form-item>
    <el-form-item
      label="备注"
      prop="remark"
    >
      <el-input
        type="textarea"
        :rows="2"
        v-model="form.remark"
        :disabled="isView"
      ></el-input>
    </el-form-item>
    <el-form-item
      v-if="isView">
      <el-button
        type="primary"
        @click="close()"
        size="medium"
      >确 定
      </el-button>
    </el-form-item>
    <el-form-item v-else>
      <el-button
        type="primary"
        @click="submit()"
        size="large"
      >确 定
      </el-button>
      <el-button
        @click="close()"
        size="large"
      >取 消
      </el-button>
    </el-form-item>
  </el-form>
</template>
